import router from "@/router";
import { RouterModel } from "./../models/routerModel";
import User from "@/api/user";
import { routes } from "@/router/common";

export function listToTree(list: RouterModel[], tree: any[], parentId: number) {
  list?.forEach((item: any) => {
    if (item.parentId === parentId) {
      const child = {
        ...item,
        children: [],
      };
      listToTree(list, child.children, item.id!);
      tree.push(child);
    }
  });
}

export async function generatorDynamicRouter() {
  const arr: RouterModel[] = [];
  const menu_result: RouterModel[] = (await User.getUserMenu()).data?.data;
  listToTree(menu_result, arr, 0);
  generator(arr);
  return arr;
}

export const generator = (routerMap: RouterModel[], parent?: any) => {
  console.log("....", routerMap);

  return routerMap.map((item) => {
    const { componentPath, component, meta, path, redirect, permission } = item;
    const routes: {
      path: string;
      name: string;
      children: any[];
      component: Function;
    } = {
      path: path,
      name: item.id.toString(),
      component: () => import(`@/views/${item.component}`),
      children: [],
    };

    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      routes.children = generator(item.children, routes);
    }

    return routes;
  });
};
